package com.mezz.bones.framework.core.biz.chain;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class BizHandlerChain<T extends BizContext> {

    private final T context;

    private BizHandlerChain(T context) {
        this.context = context;
    }

    public static <T extends BizContext> BizHandlerChain<T> of(T context) {
        return new BizHandlerChain<>(context);
    }

    private final List<BizHandler<T>> handlers = new ArrayList<>();

    @SafeVarargs
    public final void addHandler(BizHandler<T>... handlers) {
        this.handlers.addAll(Arrays.stream(handlers).collect(Collectors.toList()));
    }

    public void doBizHandler() {

        for (BizHandler<T> handler : handlers) {

            log.debug("===start=== biz handler[{}], context:[{}]",handler.getHandlerName(),context);

            if (handler.breakChain(context)) {
                log.debug("===break=== biz handler[{}], context:[{}]",handler.getHandlerName(),context);
                return;
            }

            if (handler.skip(context)) {
                log.debug("===skip=== biz handler[{}], context:[{}]",handler.getHandlerName(),context);
                continue;
            }

            handler.handle(this.context);
            log.debug("===end=== biz handler[{}], context:[{}]",handler.getHandlerName(),context);

        }
    }
}
